<template>
    <div class="login-container">
      <div class="login-card">
        <h2 class="login-title">登录</h2>
        <form class="login-form">
          <div class="form-group">
            <label for="username">账号</label>
            <input type="text" id="username" v-model="username" class="form-control" />
          </div>
          <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" v-model="password" class="form-control" />
          </div>
          <button type="submit" class="btn btn-primary" @click.prevent="handleSubmit">登录</button>
        </form>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { useAuthStore } from '@/stores/auth';
  import { login } from '@/api/loginApi';
  
  const username = ref('');
  const password = ref('');
  const router = useRouter();
  const authStore = useAuthStore();
  
  const handleSubmit = async () => {
    try {
      const response = await login({
        username: username.value,
        password: password.value
      });
      console.log('Login response:', response);
  
      if (response.code === 200) {
        const { user, token } = response.data;
        sessionStorage.setItem('Token', token);  // 或者 sessionStorage
        console.log('Setting auth with:', { user, token });
        authStore.setAuth(user,token);
  
        // 登录成功后跳转到首页
        router.push('/');
      } else {
        alert(response.message || '登录失败，请检查账号和密码');
      }
    } catch (error) {
      console.error('Login failed:', error);
      alert('登录失败，请检查账号和密码');
    }
  };
  </script>
  
  <style scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f0f0f0;
  }
  
  .login-card {
    background-color: #fff;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    width: 100%;
    text-align: center;
  }
  
  .login-title {
    font-size: 24px;
    margin-bottom: 20px;
    color: #333;
  }
  
  .form-group {
    margin-bottom: 15px;
    text-align: left;
  }
  
  .form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    color: #555;
  }
  
  .form-control {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 16px;
    transition: border-color 0.3s ease;
  }
  
  .form-control:focus {
    border-color: #007bff;
    outline: none;
  }
  
  .btn {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .btn-primary {
    background-color: #007bff;
    color: #fff;
  }
  
  .btn-primary:hover {
    background-color: #0056b3;
  }
  </style>